<?

include($_SERVER['DOCUMENT_ROOT'].'/includes/functions.inc.php');
include($_SERVER['DOCUMENT_ROOT'].'/portals/config.php');
include($_SERVER['DOCUMENT_ROOT'].'/groups/database.php');

if (false) {
	init_session();

	if (empty($_SESSION['user_id'])) {
		include($_SERVER['DOCUMENT_ROOT'].'/portals/login.inc.php');
		exit;
	}
}

include($_SERVER['DOCUMENT_ROOT'].'/portals/filter.libs.php');

$id = intval(@$_GET['id']);
if ($id) {
	$sql = array();
	
	$sql['columns'] = 'portal.*,user.realname';
	$sql['tables'] = array('portal');
	$sql['tables'][] = "left join `user`  USING (user_id)";

	$sql['wheres'] = array('status_id = 1');
	$sql['wheres'][] = "portal_id = $id";
	
	$query = sqlMakeQuery($sql);
	
	$c = getrow($query);


	if (empty($c)) 
		die("404 Not Found - We dont have this portal?");

	
	$n = empty($_GET['n'])?800:abs(intval($_GET['n']));
	
	print addNewImages($id,$n)." images found for $id<br>\n";
	queryExecute("UPDATE `filter` SET last_run = NOW(),updated=updated WHERE portal_id = $id");
	queryExecute("UPDATE `portal` SET last_fetched = NOW(),updated=updated WHERE portal_id = $id");
	queryExecute("DELETE FROM active_cache WHERE portal_id = $id");	
} else {

	//auto!



	$sql = "SELECT portal_id,filter_id FROM `filter` WHERE value != '' AND last_run < date_sub(now(),interval 12 hour) AND type = 'any' GROUP BY portal_id";

	$portals = getAssoc($sql);

	foreach ($portals as $id => $filter) {

		print addNewImages($id,1000)." images found for $id<br>\n";
		queryExecute("UPDATE `filter` SET last_run = NOW(),updated=updated WHERE portal_id = $id");
		queryExecute("UPDATE `portal` SET last_fetched = NOW(),updated=updated WHERE portal_id = $id");
		queryExecute("DELETE FROM active_cache WHERE portal_id = $id");
	}

}
